<?php
namespace app\admin\controller;

use app\admin\model\Role;
use app\admin\service\Menus;
use Atlaxy\Controller;
use Atlaxy\Node;
use think\facade\Session;

class Base extends Controller
{
    public $menus;
    public $routeUri;
    public $group;
    public $urls;
    protected function initialize()
    {
        $this->checkLogin();
        $this->getRouteinfo();
        $this->getMenus();
        $this->checkAuth();
    }

    private function checkAuth()
    {
        $url = strtolower($this->request->controller())."/".strtolower($this->request->action());
        // 如果方法不需要权限
        $authNodes = Node::instance()->getMethods();
        
        if(isset($authNodes[$url])){
            $this->request->title = $authNodes[$url]['title'];
        }
        if(isset($authNodes[$url]) && !$authNodes[$url]['isauth']){
            return true;
        }
        // 如果方法需要权限
        if(!in_array($url,$this->urls) && $this->user->id != 10000){
            if($this->request->isAjax()) $this->jsonFail("无权进行此操作");
            else die("无权进行此操作");
        }
    }
    private function getMenus(){
        $role = Role::find($this->user->role_id);
        $this->urls = $role ? explode(',',$role->urls) : [];
        $this->menus = Menus::getInstance()->getMenus($this->routeUri, $this->group,$this->urls);
        // halt($this->menus);
    }
    /**
     * 解析当前路由参数 （分组名称、控制器名称、方法名）
     */
    protected function getRouteinfo()
    {
        // 控制器名称
        $this->controller = strtolower($this->request->controller());
        // 方法名称
        $this->action = $this->request->action();
        // 控制器分组 (用于定义所属模块)
        $groupstr = strstr($this->controller, '.', true);
        $this->group = $groupstr !== false ? $groupstr : $this->controller;
        // 当前uri
        $this->routeUri = $this->controller . '/' . $this->action;
    }
    private function checkLogin()
    {
        $this->user = Session::get('user');
        if(!$this->user){
            if($this->request->isAjax()){
                $this->jsonFail("登陆已失效");
            }else{
                $this->redirect('user/login');
            }
        }
    }
}